package com.example.learningnote.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.widget.Toast;

// 系统广播
public class BatteryReceiver extends BroadcastReceiver {
    private final BatteryLevelListener listener;

    public interface BatteryLevelListener {
        void onBatteryLevelChanged(int level, boolean isLow);
    }

    public BatteryReceiver(BatteryLevelListener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            int batteryPct = (int) ((level / (float) scale) * 100);
            boolean isLow = batteryPct < 20;

            if (isLow) {
                Toast.makeText(context, "Battery low: " + batteryPct + "%", Toast.LENGTH_SHORT).show();
            }

            if (listener != null) {
                listener.onBatteryLevelChanged(batteryPct, isLow);
            }
        }
    }
}
